package com.redxiii.spike.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.redxiii.spike.api.communication.CommunicationService;
import com.redxiii.spike.api.message.ImMessage;
import com.redxiii.spike.api.message.Message;
import com.redxiii.spike.api.message.MessageHandler;
import com.redxiii.spike.util.core.EngineSession;

public class IMHandler implements MessageHandler {

	private Map<String,ImMessage> lastMessages = new HashMap<String, ImMessage>();
	
	@Override
	public void init(CommunicationService service) {
	}

	@Override
	public void close() {
		
	}

	@Override
	public boolean handle(Message message) {
		
		CommunicationService service = EngineSession.getCommunicationService();
		
		// Handler some few simple messages
		if (message instanceof ImMessage) {
			ImMessage imMessage = (ImMessage) message;
			String remoteid = imMessage.getRemoteId();
			String body = imMessage.toText().toString();
			
			if (body.equals(">redo")) {
				ImMessage last = lastMessages.get(remoteid);
				if (last != null)
					service.getIncome().offer(last);
				
				return true;
			}
			
			if (body.equals(">spy")) {
				StringBuilder builder = new StringBuilder("Last Messages:\r\n");
				for (Entry<String, ImMessage> entry : lastMessages.entrySet()) {
					builder
						.append(entry.getKey())
						.append("= *\"")
						.append(entry.getValue().toText())
						.append("\"* \r\n");
				}
				service.reply(message, builder);
				return true;
			}
			
			lastMessages.put(remoteid, imMessage);
			return false;
		}
		return false;
	}
}
